<?php defined('SYSPATH') or die('No direct script access.');

class Model_Services_PathologyPatient extends Model implements Jqgrid_GridListener{
	
	public $id_patient;
	public $pathology_patient = NULL;
	
	public function __construct($id=false){
		$this->id_patient = $id;
	}	
	
	public function count($criteria = false){
		return ORM::factory("dao_pathologypatient")->where("patient_id","=",$this->id_patient)->count_all();
	}
	
	public function getList($criteria = false){
		if (!$criteria)	$pathologies_patient_list = ORM::factory("dao_pathologypatient")->where("patient_id","=",$this->id_patient)->find_all()->as_array();
		else $pathologies_patient_list = ORM::factory("dao_pathologypatient")->where("patient_id","=",$this->id_patient)->order_by($criteria->sidx,$criteria->sord)->limit($criteria->limit)->offset($criteria->calcOffset())->find_all()->as_array();
	
		$dataset = array();
		foreach ($pathologies_patient_list as $pathology_patient){
			$dataset[$pathology_patient->id] = array(	$pathology_patient->pathology->pathology_name,
														$pathology_patient->currently,
														Helper_Service::factory("patient",$this->id_patient)->getAge() - $pathology_patient->age_at_start,
														$pathology_patient->inherited,
														$pathology_patient->patient_id);
		}
				
		return $dataset;
	}
	
	
			
	public function getCondition($orderfield, $ordertype, $start,$limit){
		return ORM::factory("dao_pathologypatient")->where("patient_id","=",$this->id_patient)->order_by($orderfield,$ordertype)->limit($limit)->find_all()->as_array();
	}
		
	public function get($id){ return ORM::factory("dao_pathologypatient")->find($id);}
	
	public function getAll(){}
		
	public function save($id,array $data){
				
		//if ($id && !is_array($id)) return Fire::log("Error, se esperaba clave compuesta");
		$this->pathology_patient = ($id) ? ORM::factory("dao_pathologypatient",$id) : ORM::factory("dao_pathologypatient");
		
		//hacer funcion para pasar de string a numeros (una funcion sanitize input)
		$this->pathology_patient->pathology_id = intval($data['pathology_id']);
		$this->pathology_patient->patient_id = ($id) ? intval($data['patient_id']) : $this->id_patient;
		$this->pathology_patient->currently = intval($data['currently']);
		$this->pathology_patient->age_at_start = intval($data['age_at_start']);
		$this->pathology_patient->inherited = intval($data['inherited']);
				
		$this->pathology_patient->save();
		return $this->pathology_patient->id;
	}

	public function delete($id){
		$this->pathology_patient = ORM::factory("dao_pathologypatient",$id);
		$this->pathology_patient->delete();
		return $id;
	}
	
	/**
	 * 
	 * return all patient pathologies 
	 * @param int $id
	 */
	public function getPatientPathologies($id=false){
		return ORM::factory("dao_pathologypatient")->where("patient_id","=",(!$id)?$this->id_patient:$id)->find_all()->as_array();
	}
	
}
?>
